<template>
  <el-card>
    <el-form ref="Formdata" :rules="rules" label-width="100px" :model="goodsData">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基本信息" name="first">
          <el-form-item label="一级分类" prop="first_cateid">
            <el-select
              v-model="goodsData.first_cateid"
              placeholder="请选择"
              @change="getCateListid"
            >
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.catename"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类" prop="second_cateid">
            <el-select v-model="goodsData.second_cateid" placeholder="请选择">
              <el-option
                v-for="item in secondCateList"
                :key="item.id"
                :value="item.id"
                :label="item.catename"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="goodsname" label="商品名称">
            <el-input
              v-model="goodsData.goodsname"
              placeholder="请输入商品名称"
            ></el-input>
          </el-form-item>
          <el-form-item prop="market_price"  label="商品价格">
            <el-input
              v-model="goodsData.market_price"
              placeholder="请输入商品价格"
            ></el-input>
          </el-form-item>
          <el-form-item label="市场价格" prop="price">
            <el-input
              v-model="goodsData.price"
              placeholder="请输入市场价格"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品图片" prop="img">
            <!--  el-upload无法进行双向数据绑定-->
            <el-upload
              action="#"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :auto-upload="false"
              :limit="1"
              :on-exceed="limitTips"
              :on-change="fileChange"
              :file-list="imgChan"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
          <el-form-item label="商品规格" prop="specsid">
            <el-select @change="specsListid" v-model="goodsData.specsid">
              <el-option
                v-for="item in specsList"
                :key="item.id"
                :value="item.id"
                :label="item.specsname"
              ></el-option>
            </el-select>
          </el-form-item  >
          <el-form-item label="规格属性值" prop="specsattr">
            <el-select v-model="goodsData.specsattr" label="请选择规格属性值" multiple="">
              <el-option
                v-for="(item, index) in chiYanList"
                :key="index"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
            <!-- 这里的名字为什么是item?? -->
          </el-form-item>
          <el-form-item label="是否新品" prop="isnew">
            <el-radio-group v-model="goodsData.isnew">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">不是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否新品" prop="ishot">
            <el-radio-group v-model="goodsData.ishot">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="goodsData.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品描述" name="second">
          <vueWangeditor ref="description" id="description" width="100%" style="height:=500px"></vueWangeditor>
        </el-tab-pane>
      </el-tabs>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">更新</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { getCateList } from "../../request/categroy";
import { getSpecsList } from "../../request/specs";
import {getGoodsById} from '../../request/goods'
// 引入富文本编辑器
import vueWangeditor from 'vue-wangeditor'
export default {
  // 注册富文本编辑器
  components:{vueWangeditor},
  data() {
    return {
      activeName: "first",
      // 上传图片相关的方法
        dialogImageUrl: '',
        dialogVisible: false,
      // 一级分类
      cateList: [],
      // 图片更新相关
      imgChan:[],
      
      //  二级分类
      secondCateList: [],
      specsList: [],
      chiYanList: [],
      goodsData: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        market_price: "",
        price: "",
        img: "",
        description: "",
        specsid: "",
        specsattr: "",
        isnew: "",
        ishot: "",
        status: "",
      },
      rules:{
        first_cateid: {required:true,message:'请输入一级栏目'},
        second_cateid: {required:true,message:'请输入二级栏目'},
        goodsname: {required:true,message:'请输入商品名称'},
        market_price: {required:true,message:'请输入市场价格'},
        price: {required:true,message:'请输入价格'},
        // img: {required:true,message:'请选择图片'},
        // description: {required:true,message:'请输入商品详情'},
        specsid: {required:true,message:'请输入规格'},
        specsattr: {required:true,message:'请输入规格属性'},
        isnew: {required:true,message:'请选择是否新品'},
        ishot: {required:true,message:'请选择是否热卖'},
        status: {required:true,message:'请选择状态'},
      }
    };
  },
  methods: {
    // 这里必须有一个事件函数，即使它是空的，这样做是为了定义
    getCateListid(id){
      const index = this.cateList.findIndex((item) => item.id === id);
      this.secondCateList = this.cateList[index].children;
    },
    specsListid(id,flag=true){
      const suoindex = this.specsList.findIndex((item) => item.id === id);
      this.chiYanList = this.specsList[suoindex].attrs;
      // 手动点击规格下拉框时，将已经有的置空
      // console.log(this.goodsData.specsattr)
      // console.log(flag)
      if(flag){
        this.goodsData.specsattr=[]
      }
    },
        // 根据id拿取颜色和尺寸下的详细分类
    // specsListid(id) {
    //   const suoindex = this.specsList.findIndex((item) => item.id === id);
    //   this.chiYanList = this.specsList[suoindex].attrs;
    // },
    // 直接显示图片
    // imgChange(file){
      
    // },
    // 拿到商品，怎么拿，通过id
      // async getGoodsById(){
      //   //   商品修改自动显示，要拿id
      //   //   直接在路由对象里拿id
      //   const info=await getGoodsById(this.$route.params.id)
      //   // 出现页面直接追加
      //   if(info){ //如果接收到了这个商品的id的话
      //     this.goodsData=info
      //     // 更新图片
      //     this.imgChan=info.img===''?[]:[{url:this.$imgBaseURL+info.img}]
      //   }
      // },
     handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
    //图片相关的方法
    fileChange(file){
      console.log(file)
      // 将图片的原始信息赋给img
      this.goodsData.img=file.raw
    },
    limitTips(){
      this.$error('亲，这里最多上传一张图片哦')
    },
    // 监听一级分类
    getCateListid(id) {
      const index = this.cateList.findIndex((item) => item.id === id);
      this.secondCateList = this.cateList[index].children;
    },

    handleClick(tab, event) {
      console.log(tab, event);
    },
    async getDatainit() {
      const [cateList, specsList,goodsData] = await this.$http.all([
        getCateList(),
        getSpecsList(),
        getGoodsById(this.goodsData.id)
      ]);
      // 分类
      this.cateList = cateList;
      // 规格
      this.specsList = specsList;
      // 编辑的商品信息
      this.goodsData=goodsData
      // 打开就显示的图片
      this.imgChan=this.goodsData.img===''?[]:[{url:this.$imgBaseURL+this.goodsData.img}]
      //注意放的位置  显现二级分类  触发一次一级分类
      this.getCateListid(this.goodsData.first_cateid)
      // 这里传一个false，也就是说，那个置空的逻辑，只能在手动，即点击时触发，而在生命周期的阶段里，我是不需要它触发的
      this.specsListid(this.goodsData.specsid,false)
      // 这里不能显示是数据类型的问题，要转换成数组
      this.goodsData.specsattr=this.goodsData.specsattr.split(',')
      // 商品描述 类似于双向数据绑定 ??
      this.$refs.description.setHtml(goodsData.description)
    },
      // 点击提交到接口的数据
  submitForm(){
    // 表单终极效验的方法，要使用ref操作虚拟DOM对象
    this.$refs.Formdata.validate(async valid=>{
      if(valid){
        //若是有图片的上传，就必须用FormData
        const fd=new FormData()
        for(let key in this.goodsData){
          fd.append(key,this.goodsData[key])
        }
        fd.append('id',this.$route.params.id)
        // 将富文本编辑器的内容追加到fd对象中
        fd.append('description',this.$refs.description.getHtml())
        const res=await this.$http.post('/api/goodsedit',fd)
        console.log(res)
        if(res.code===200){
          this.$success('修改成功')
          // 重定向
          this.$router.push('/goods')
        }else{
          return this.$error('修改失败')
        }
      
      }
    })
  }
  
  },
  created() {
    this.goodsData.id=this.$route.params.id
    this.getDatainit();
    
  },

};
</script>

<style lang="less" scoped>
.el-input {
  width: 400px;
}
</style>